package com.yjzx.util.common.util.batch.mergingLimit;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author guozhi
 * @date 2025/1/13
 * @description paramView
 */
public class MergingView<T, U extends Comparable<U>,R> implements NotNullParam {
    final T param;
    /**
     * 需要判断大小的起始获取
     */
    private final Function<T, U> uStartGet;
    /**
     * 需要判断大小的起始修改
     */
    private final BiConsumer<T, U> uStartSet;
    /**
     * 需要判断大小的结束获取
     */
    private final Function<T, U> uEndGet;
    /**
     * 需要判断大小的结束修改
     */
    private final BiConsumer<T, U> uEndSet;

    private final MergingSlotManager<T, U, R> mergingSlotManager;

    public MergingView(T param, Function<T, U> uStartGet, BiConsumer<T, U> uStartSet, Function<T, U> uEndGet, BiConsumer<T, U> uEndSet, MergingSlotManager<T, U, R> mergingSlotManager) {
        this.param = param;
        this.uStartGet = uStartGet;
        this.uStartSet = uStartSet;
        this.uEndGet = uEndGet;
        this.uEndSet = uEndSet;
        this.mergingSlotManager = mergingSlotManager;
        check();
    }

    public T getParam() {
        return param;
    }

    public U getStart() {
        return uStartGet.apply(param);
    }

    public U getEnd() {
        return uEndGet.apply(param);
    }

    public void setStart(U start) {
        uStartSet.accept(param, start);
    }

    public void setEnd(U end) {
        uEndSet.accept(param, end);
    }
    public List<R> toDataMerging() {
        U end = this.getEnd();
        T param = this.getParam();
        ArrayList<R> list = new ArrayList<>();
        for (MergingSlot<T, U, R> mergingSlot : mergingSlotManager) {
            U start = this.getStart();
            if (mergingSlot.getEnd().compareTo(start) > 0 && mergingSlot.start.compareTo(end) < 0) {
                this.setEnd(mergingSlot.end.compareTo(end) > 0 ? end : mergingSlot.end);
                list.add(mergingSlot.result.apply(param)) ;
                this.setStart(mergingSlot.end);
            }
        }
        return list;
    }

}
